<template>
  <div id="equipmentManagePage">
    <div style="display: flex; align-items: center; justify-content: space-between;">
      <!-- 搜索表单 -->
      <a-form ref="formRef" layout="inline" :model="searchParams" @finish="doSearch">
        <a-form-item label="器材名称" name="equipmentName">
          <a-input v-model:value="searchParams.equipmentName" placeholder="器材名称" allow-clear />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="resetSearch">重置</a-button>
            <a-button type="primary" html-type="submit">搜索</a-button>
          </a-space>
        </a-form-item>
      </a-form>
      <a-button type="primary" :href="`/equipment/add_equipment`">新增</a-button>
    </div>
    <div>
      <!-- 一级分类 -->
      <a-tabs v-model:activeKey="selectedCategory" @change="handleCategoryChange">
        <a-tab-pane key="0" tab="全部" />
        <a-tab-pane v-for="category in categoryList" :key="category.id" :tab="category.categoryName" />
      </a-tabs>

      <!-- 二级分类 -->
      <div v-if="selectedCategory !== '0' && subCategoryList.length > 0">
        <a-tabs v-model:activeKey="subSelectedCategory" @change="doSearch">
          <a-tab-pane v-for="subCategory in subCategoryList" :key="subCategory.id" :tab="subCategory.categoryName" />
        </a-tabs>
      </div>
    </div>
    <div class="tag-bar">
      <span style="margin-right: 8px">标签： </span>
      <a-space :size="[0, 8]" wrap>
        <a-checkable-tag
          v-for="(tag, index) in tagList"
          :key="tag.id"
          v-model:checked="selectedTagList[index]"
          @change="doSearch"
        >
          {{ tag.labelName }}
        </a-checkable-tag>
      </a-space>
    </div>
    <div style="margin-bottom: 16px"></div>
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
      :loading="loading"
    >
      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'imageUrl'">
          <a-image :src="record.imageUrl" width="120px" />
        </template>
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-if="column.dataIndex === 'updateTime'">
          {{ dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button
              :href="`/equipment/equipmentInformation?equipmentId=${record.id}`" target="_blank">查看
            </a-button>
            <!-- 操作按钮 -->
            <!-- 在操作按钮处传递record对象 -->
            <a-button type="primary" v-if="editExist" @click="showAddModal(record)">
              <template #icon>
                <plus-outlined />
              </template>
              新建订单
            </a-button>
            <a-button v-if="editExist" type="link"
                      :href="`/equipment/add_equipment?id=${record.id}`" target="_blank">编辑
            </a-button>
            <a-popconfirm title="你确定要删除吗?" @confirm="doDelete(record.id)">
              <a-button danger v-if="editExist">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { deleteUsingPost, listUsingPost } from '@/api/equipmentInfoController.ts'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { queryCategoryByPrimaryUsingPost, queryPrimaryCategoryUsingGet } from '@/api/equipmentCategoryController.ts'
import { queryAllUsingGet } from '@/api/equipmentLabelController.ts'
import EquipmentCategoryDTO = API.EquipmentCategoryDTO
import EquipmentLabelDTO = API.EquipmentLabelDTO
import { addOrdersUsingPost, updateOrdersUsingPost } from '@/api/ordersController.ts'
import { listUserVoByPageUsingPost1 } from '@/api/companyController.ts'


const userLogin = useLoginUserStore().loginUser
const userLoginRole = userLogin.userRole ? userLogin.userRole.split(',').map(role => role.trim()) : []
let editExist = false

if (!userLogin || !userLogin.userRole) {
  // 用户未登录
  editExist = false
} else if (userLoginRole.includes('0') || userLoginRole.includes('1')) {
  // 用户登录且角色为 '0' 或 '1'
  editExist = true
}

// 分类标签获取
const categoryList = ref<EquipmentCategoryDTO[]>([])
const selectedCategory = ref<number>(0)
const subCategoryList = ref<EquipmentCategoryDTO[]>([])
const subSelectedCategory = ref<number>(0)
const tagList = ref<EquipmentLabelDTO[]>([])
const selectedTagList = ref<boolean[]>([])
//编辑订单
const modalVisible = ref(false)
const modalTitle = ref('新建订单')
// 表单状态
// 修改formState类型定义
const formState = ref<API.OrdersDTO & {
  equipmentId?: number;
  equipmentName?: string;
  equipmentPrice?: number;
}>({})

// 公司名称
const companyList = ref([])
const columns = [
  {
    title: 'id',
    dataIndex: 'id'
  },
  {
    title: '器材名称',
    dataIndex: 'equipmentName'
  },
  {
    title: '器材价格',
    dataIndex: 'equipmentPrice'
  },
  {
    title: '描述',
    dataIndex: 'description'
  },
  {
    title: '器材图片',
    dataIndex: 'imageUrl'
  },
  {
    title: '使用说明',
    dataIndex: 'equipmentInstructions'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime'
  },
  {
    title: '库存',
    dataIndex: 'quantity'
  },
  {
    title: '操作',
    key: 'action'
  }
]

const dataList = ref<API.AuthUserVO[]>([])
const total = ref(0)
const searchParams = reactive<API.EquipmentInfoDTO>({
  current: 1,
  pageSize: 10
})
const loading = ref(false)
const fetchData = async () => {
  try {
    loading.value = true
    const params = {
      ...searchParams,
      labelIds: [] as number[]
    }
    //处理父子分类
    if (subSelectedCategory.value !== 0) {
      params.categoryId = subSelectedCategory.value
    }
    if (selectedCategory.value == 0) {
      params.categoryId = null
    }
    //处理标签
    // 收集选中的标签ID
    params.labelIds = selectedTagList.value
      .map((checked, index) => checked ? tagList.value[index]?.id : null)
      .filter(id => id !== null) as number[]

    const res = await listUsingPost(params)
    if (res.data.code === 0 && res.data.data) {
      dataList.value = res.data.data.result.map((item) => ({
        ...item,
        key: item.id
      }))
      total.value = res.data.data.total ?? 0
    } else {
      message.error('获取数据失败: ' + res.data.message)
    }
  } catch (error) {
    message.error('请求失败: ' + error)
  }
  loading.value = false
}

const formRef = ref()
// 重置搜索栏

const resetSearch = () => {
  formRef.value.resetFields()
  // 重置标签选中状态
  selectedTagList.value = new Array(tagList.value.length).fill(false)
  selectedCategory.value = 0
  doSearch()
}

onMounted(() => {
  getTagCategoryOptions()
  fetchData()
})
//展示订单
// 修改showAddModal方法
// const showAddModal = (equipmentInfo: API.EquipmentInfoDTO) => {
//   modalVisible.value = true
//   isEdit.value = false
//   modalTitle.value = '新建订单'
//   formState.value = {
//     ...formState.value,
//     equipmentId: equipmentInfo.id,
//     equipmentName: equipmentInfo.equipmentName,
//     equipmentPrice: equipmentInfo.equipmentPrice, // 添加设备价格
//     quantityPurchased: 1 // 默认数量设为1
//   }
//   calculateTotal() // 初始化时计算总金额
// }
const showAddModal = async (equipmentInfo: API.EquipmentInfoDTO) => {
  await loadCompanies() // 确保加载公司数据
  modalVisible.value = true
  modalTitle.value = '新建订单'
  formState.value = {
    ...formState.value,
    equipmentId: equipmentInfo.id,
    equipmentName: equipmentInfo.equipmentName,
    equipmentPrice: Number(equipmentInfo.equipmentPrice), // 确保为数字类型
    quantityPurchased: 1,
    companyId: undefined // 重置公司选择
  }
  calculateTotal()
}

// 计算总金额方法
const calculateTotal = () => {
  if (formState.value.equipmentPrice && formState.value.quantityPurchased) {
    formState.value.totalMoney = Number(
      (formState.value.equipmentPrice * formState.value.quantityPurchased).toFixed(2)
    )
  }
}

// 监听数量和价格变化
watch(
  () => [formState.value.quantityPurchased, formState.value.equipmentPrice],
  () => {
    calculateTotal()
  }
)

// 提交表单
// const handleModalOk = async () => {
//   try {
//     debugger
//     await addOrdersUsingPost(formState)
//     message.success('操作成功')
//     resetForm()
//     fetchData()
//   } catch (error) {
//     message.error('操作失败')
//   }
// }
const handleModalOk = async () => {
  try {
    // 提取必要字段，构建纯对象
    const requestData = {
      equipmentId: formState.value.equipmentId,
      companyId: formState.value.companyId,
      equipmentPrice: formState.value.equipmentPrice,
      quantityPurchased: formState.value.quantityPurchased,
      totalMoney: formState.value.totalMoney
    }

    // 调用接口时传递纯对象
    await addOrdersUsingPost(requestData)
    message.success('操作成功')
    resetForm()
    fetchData()
  } catch (error) {
    message.error(`操作失败: ${error.message}`)
  }
}


// 重置表单
const resetForm = () => {
  modalVisible.value = false
  Object.keys(formState).forEach(key => {
    formState[key] = undefined
  })
}

// 加载公司数据
const loadCompanies = async () => {
  try {
    const res = await listUserVoByPageUsingPost1({ pageSize: 100 })
    companyList.value = res.data.data.records
  } catch (error) {
    message.error('公司数据加载失败')
  }
}

const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: +total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共${total}条`
  }
})

const doTableChange = (page: any) => {
  searchParams.current = page.current
  fetchData()
}

const doSearch = () => {
  searchParams.current = 1
  fetchData()
}
//获取标签和分类
const getTagCategoryOptions = async () => {
  const res = await queryPrimaryCategoryUsingGet()
  const resd = await queryAllUsingGet()
  if (res.data.code === 0 && res.data.data && resd.data.code === 0 && resd.data.data) {
    categoryList.value = res.data.data ?? []
    tagList.value = resd.data.data ?? []
    // 初始化selectedTagList为与标签数量相同的false数组
    selectedTagList.value = new Array(tagList.value.length).fill(false)
  }
}

const handleCategoryChange = async () => {
  console.log('selectedCategory.value', selectedCategory.value)
  if (Number(selectedCategory.value) === 0) {
    await doSearch()
    return
  }
  const res = await queryCategoryByPrimaryUsingPost({ parentId: selectedCategory.value })
  if (res.data.code === 0 && res.data.data) {
    subCategoryList.value = res.data.data ?? []
  }
}

const doDelete = async (id: string) => {
  if (!id) {
    return
  }
  try {
    const res = await deleteUsingPost({ id })
    searchParams.current =
      total.value % searchParams.pageSize == 1
        ? searchParams.current - 1
        : searchParams.current
    if (res.data.code === 0) {
      message.success('删除成功')
      fetchData()
    } else {
      message.error('删除失败: ' + res.data.message)
    }
  } catch (error) {
    message.error('请求失败: ' + error)
  }
}

</script>

<style lang="less" scoped>
.editable-cell {
  position: relative;

  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    margin-top: 4px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}
</style>
